package org.dh2580.delay.queue.bean.task;

import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.dh2580.delay.queue.bean.db.DBUtil;
import org.dh2580.delay.queue.bean.model.Ack;


/**
 * @Author: hao.deng
 * @Date: 2019/5/15-下午1:44
 */
public class AckCallableTask implements Runnable {
    private Long msgId;

    private Future<Ack> future;

    private Integer maxExpiredMinute;

    private static final String INIT_SQL_TPL = "UPDATE tb_delay_msg_queue SET ack_state = 0 WHERE id = ?";

    private static final String ACKED_SQL_TPL = "UPDATE tb_delay_msg_queue SET ack_state = 2 WHERE id = ?";

    private static final String ABANDON_SQL_TPL = "UPDATE tb_delay_msg_queue SET ack_state = 3 WHERE id = ?";

    public AckCallableTask(Long msgId, Future<Ack> future, Integer maxExpiredMinute) {
        this.msgId = msgId;
        this.future = future;
        this.maxExpiredMinute = maxExpiredMinute;
    }

    @Override
    public void run() {
        try {
            Ack ack = future.get(maxExpiredMinute, TimeUnit.MINUTES);

            if (ack == Ack.OK) {

                DBUtil.execute(ACKED_SQL_TPL, msgId);

            } else if (ack == Ack.FAIL_RETRY) {

                DBUtil.execute(INIT_SQL_TPL, msgId);

            } else if (ack == Ack.FAIL_NO_RETRY) {

                DBUtil.execute(ABANDON_SQL_TPL, msgId);

            }

        } catch (Exception ex) {
            //do nothing
        }
    }
}
